package todo;


import se.lth.cs.realtime.*;
import se.lth.cs.realtime.event.AckEvent;
import done.AbstractWashingMachine;


public class TemperatureController extends PeriodicThread {
	AbstractWashingMachine washingMachine;
	int currentMode;
	double temp;
	double downTemp;
	RTThread source;
	double speed;
	boolean isAcked;
	// TODO: add suitable attributes

	public TemperatureController(AbstractWashingMachine mach, double speed) {
		super((long) (1000/speed)); // TODO: replace with suitable period
		this.speed = speed;
		washingMachine = mach;
		currentMode = TemperatureEvent.TEMP_IDLE;
	}

	public void perform() {
		TemperatureEvent currentEvent = (TemperatureEvent) mailbox.tryFetch();
		
		if (currentEvent != null){
			currentMode = currentEvent.getMode();
			isAcked = false;
			temp = currentEvent.getTemperature() - 0.2;
			downTemp = currentEvent.getTemperature() - 1.8;
			source = (RTThread) currentEvent.getSource();
		}
		
		switch (currentMode){
		
		case TemperatureEvent.TEMP_IDLE:
			washingMachine.setHeating(false);
			break;
			
		case TemperatureEvent.TEMP_SET:
			if (washingMachine.getWaterLevel() == 0.0){
				System.out.println("You are not allowed to heat the machine when there is no water");
				washingMachine.setHeating(false);
			} else {
				if (washingMachine.getTemperature() > temp){
					if (!isAcked){
						source.putEvent(new AckEvent());
					}
					isAcked = true;
					washingMachine.setHeating(false);
					break;
				} else if (washingMachine.getTemperature() < downTemp){
					washingMachine.setHeating(true);
				}
			}
			
			break;
		}
		// TODO: implement this method
	}
}
